package com.ebelter.seneo.ui.activitys;


import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.ebelter.btcomlib.models.db.products.seneo.SeneoUserMeasureUploadData;
import com.ebelter.btcomlib.models.db.products.seneo.SeneoUserinfos;
import com.ebelter.btcomlib.models.eventbus.CommonEventBus;
import com.ebelter.btcomlib.models.https.NetUtils;
import com.ebelter.btcomlib.models.https.interfaces.HttpResponse;
import com.ebelter.btcomlib.models.https.responses.BaseResponse;
import com.ebelter.btcomlib.utils.NumUtils;
import com.ebelter.btcomlib.utils.StatusBarUtil;
import com.ebelter.btcomlib.utils.ThreadManager;
import com.ebelter.btcomlib.utils.ToastUtil;
import com.ebelter.btcomlib.utils.ViewUtils;
import com.ebelter.btcomlib.utils.log.LogUtils;
import com.ebelter.btcomlib.views.WheelView;
import com.ebelter.btcomlib.views.dialogs.TextTipDialog;
import com.ebelter.btcomlib.views.dialogs.WheelViewDialog;
import com.ebelter.btcomlib.views.dialogs.picktime2.CustomDatePicker;
import com.ebelter.seneo.R;
import com.ebelter.seneo.contants.IUserContant;
import com.ebelter.seneo.models.SeneoBTManager;
import com.ebelter.seneo.models.SeneoDbUtils;
import com.ebelter.seneo.models.SeneoNet;
import com.ebelter.seneo.ui.views.AddNameDialog;
import com.ebelter.seneo.ui.views.SeneoTipDialog2;
import com.ebelter.seneo.utils.SeneoUtils;

import org.greenrobot.eventbus.EventBus;
import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import static com.ebelter.btcomlib.views.dialogs.TextTipDialog.Gravity_BUTTOM;
import static com.ebelter.seneo.ui.activitys.SeneoMainActivity.white;

public class SeneoPeopleDetailInfoActivity extends SeneoBaseActivity implements View.OnClickListener {


    public static final String TAG = "DetailInfoActivity";

    private static final String WHICH_USERID = "1";
    ImageView top_iv;
    TextView top_tv1;
    ImageView top_iv2;

    RelativeLayout pd_name_rl;
    RelativeLayout pd_stature_rl;
    RelativeLayout pd_birthday_rl;
    RelativeLayout pd_role_rl;
    RelativeLayout pd_email_rl;
    RelativeLayout pd_passcode_rl;



    TextView pd_name_tv;
    TextView pd_stature_tv;
    TextView pd_birthday_tv;
    TextView pd_role_tv;
    TextView pd_email_tv;
    TextView set_psw_tv;
    View pd_email_v;
    View pd_p_v;
    Button pd_buttom;

    ImageView pd_iv;


    public static void openSeneoPeopleDetailInfoActivity(Activity activity, long whichId,int requestCode){
        Intent intent=new Intent(activity,SeneoPeopleDetailInfoActivity.class);
        intent.putExtra(WHICH_USERID,whichId);
        activity.startActivityForResult(intent,requestCode);
    }

    @Override
    protected int loadLayoutById() {
        return R.layout.activity_peopledetailinfo_ly;
    }


    SeneoUserinfos userinfos;
    @Override
    protected void initData() {
        long whichUserId = getIntent().getLongExtra(WHICH_USERID,-1);
        userinfos= SeneoDbUtils.getUserinfos(whichUserId);
        if (userinfos==null){
            throw new RuntimeException("逻辑出错");
        }

        if (!userinfos.isHost){//不是主用户
            ViewUtils.goneView(pd_email_rl);
            ViewUtils.goneView(pd_passcode_rl);
            ViewUtils.goneView(pd_email_v);
            ViewUtils.goneView(pd_p_v);
        }else {
            ViewUtils.goneView(top_iv2);//主用户的时候删除掉
        }


        if (whichUserId== SeneoBTManager.currentUseUserId){
            ViewUtils.goneView(top_iv2);//正在使用的时候那个删除按钮隐藏起来
        }


        ViewUtils.setTextViewStr(pd_name_tv,userinfos.nickName);
        height=userinfos.height;
        ViewUtils.setTextViewStr(pd_stature_tv,userinfos.height+" cm");
        birthday=userinfos.birthday;
        ViewUtils.setTextViewStr(pd_birthday_tv,userinfos.birthday);

        roleSelectedIndex=userinfos.athlete;
        roleSelectedIndex2=userinfos.athlete;
        ViewUtils.setTextViewStr(pd_role_tv,roleSelectedIndex==0?"Normal-Worker":"Athlete");

        if (!TextUtils.isEmpty(userinfos.email)){
            ViewUtils.setTextViewStr(pd_email_tv,userinfos.email);
        }


        ViewUtils.setImageResource(pd_iv,userinfos.sex==0?R.drawable.icon_male_set:R.drawable.icon_female_set);


    }

    @Override
    protected void initView() {

        StatusBarUtil.setColor(this,white,0);
        StatusBarUtil.setDarkStatusIcon(this,true);

        FV();
        top_iv2.setImageResource(R.drawable.ic_delete);
        setListeners();
    }

    private void setListeners() {
        top_iv.setOnClickListener(this);
        pd_name_rl.setOnClickListener(this);
        pd_stature_rl.setOnClickListener(this);
        pd_birthday_rl.setOnClickListener(this);
        pd_email_rl.setOnClickListener(this);
        pd_passcode_rl.setOnClickListener(this);
        pd_buttom.setOnClickListener(this);
        pd_role_rl.setOnClickListener(this);

        top_iv2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showDeleteTip();
            }
        });
    }

    private SeneoTipDialog2 tipDialog2;
    private void showDeleteTip() {
        tipDialog2=new SeneoTipDialog2(this, "Do you want to delete this user?");//是否删除此条记录
        tipDialog2.setListener(new SeneoTipDialog2.ICancelOkBtListener() {
            @Override
            public void cancel(Dialog dialogView) {
                dialogView.cancel();
            }

            @Override
            public void ok(Dialog dialogView, String str) {
                dialogView.cancel();
                deleteByid();
            }
        });
        tipDialog2.show();
    }

    private void deleteByid() {

        if (!NetUtils.available()){
            ToastUtil.show(R.string.Network_error);
            return;
        }

        SeneoNet.getIntance().deleteUserById(this, userinfos.user_id, new HttpResponse<BaseResponse>() {
            @Override
            public void result(boolean isRequestSuccess, String requestDes, BaseResponse baseResponse, String s) {

                LogUtils.i2(TAG,"删除用户信息 userinfos="+userinfos+"----s="+s);
                if (isRequestSuccess&&baseResponse!=null&&baseResponse.resultCode==0){
                    //删除成功


                    //用户删除了 如果有未上传的数据就删除掉
                    ThreadManager.getShortPool().execute(new Runnable() {
                        @Override
                        public void run() {
                            List<SeneoUserMeasureUploadData> list=SeneoDbUtils.getSeneoUserMeasureUploadData(userinfos.user_id);
                            if (list!=null&&list.size()>0){
                                for (int i=0;i<list.size();i++){
                                    SeneoUserMeasureUploadData item = list.get(i);
                                    if (item!=null)item.delete();
                                }
                            }
                        }
                    });



                    CommonEventBus commonEventBus=new CommonEventBus(TAG,SeneoMembersListActivity.TAG, IUserContant.ICMDS.DELETE_User_SUCCESS,"删除用户成功");
                    commonEventBus.setContent(userinfos.user_id);
                    EventBus.getDefault().post(commonEventBus);
                    ToastUtil.show(R.string.shchchg);//删除成功
                    finish();


                }else {
                    //删除失败
                    ToastUtil.show(R.string.shchshb);//删除失败
                }
            }
        });


    }

    private void FV() {

        top_iv=findViewById(R.id.top_iv);
        top_tv1=findViewById(R.id.top_tv1);
        top_iv2=findViewById(R.id.top_iv2);
        ViewUtils.displayView(top_tv1);
        ViewUtils.setTextViewStr(top_tv1,"Personal information");

        ViewUtils.displayView(top_tv1);

        pd_name_rl=findViewById(R.id.pd_name_rl);
        pd_stature_rl=findViewById(R.id.pd_stature_rl);
        pd_birthday_rl=findViewById(R.id.pd_birthday_rl);
        pd_email_rl=findViewById(R.id.pd_email_rl);
        pd_passcode_rl=findViewById(R.id.pd_passcode_rl);


        pd_name_tv=findViewById(R.id.pd_name_tv);
        pd_stature_tv=findViewById(R.id.pd_stature_tv);
        pd_birthday_tv=findViewById(R.id.pd_birthday_tv);
        pd_email_tv=findViewById(R.id.pd_email_tv);
        set_psw_tv=findViewById(R.id.set_psw_tv);

        pd_p_v=findViewById(R.id.pd_p_v);
        pd_email_v=findViewById(R.id.pd_email_v);
        pd_buttom=findViewById(R.id.pd_buttom);

        pd_role_rl=findViewById(R.id.pd_role_rl);
        pd_role_tv=findViewById(R.id.pd_role_tv);

        pd_iv=findViewById(R.id.pd_iv);
    }


    @Override
    public void onClick(View v) {

        switch (v.getId()){
            case R.id.top_iv:
                back();
                break;
            case R.id.pd_name_rl:
                showNameDialog();
                break;
            case R.id.pd_stature_rl:
                showHeightDialog();
                break;
            case R.id.pd_birthday_rl:
                showBirthdayDialog();
                break;
            case R.id.pd_role_rl:
                showRoleDialog();
                break;
            case R.id.pd_email_rl:
                break;
            case R.id.pd_passcode_rl:
                SeneoModifyPswActivity.openSeneoModifyPswActivity(this,userinfos.email,userinfos.nickName);
                break;
            case R.id.pd_buttom:
                updateUserInfo();
                break;
        }
    }



    private int roleSelectedIndex;//0普通人 ==1运动员
    private int roleSelectedIndex2;//0普通人 ==1运动员

    private void showRoleDialog() {
        roleSelectedIndex2=roleSelectedIndex;

        WheelViewDialog wheelViewDialog = new WheelViewDialog(this);
        wheelViewDialog.setGravity(Gravity_BUTTOM);
        List<String> list=new ArrayList<>();
        list.add("Normal-Worker");
        list.add("Athlete");
        wheelViewDialog.setOffeset(1);
        wheelViewDialog.setItems(list);
        wheelViewDialog.setOnWheelViewListener(new WheelView.OnWheelViewListener() {
            @Override
            public void onSelected(int selectedIndex, String item) {
                Log.i(TAG, "showRoleDialog-selectedIndex: " + selectedIndex + ", item: " + item);
                roleSelectedIndex2=selectedIndex-1;
                //selectedIndex==0普通人 ==1运动员
            }
        });


        wheelViewDialog.setListener(new TextTipDialog.ICancelOkBtListener() {
            @Override
            public void cancel(Dialog dialogView) {
                dialogView.cancel();
            }

            @Override
            public void ok(Dialog dialogView) {
                dialogView.cancel();
                roleSelectedIndex=roleSelectedIndex2;
                ViewUtils.setTextViewStr(pd_role_tv,roleSelectedIndex==0?"Normal-Worker":"Athlete");

            }
        });
        wheelViewDialog.setSelectPosition(roleSelectedIndex2);
        wheelViewDialog.show();
        wheelViewDialog.setBackgroundColor(getBaseContext().getResources().getColor(R.color.bluetheme));
    }

    String birthday;
    //展示生日对话框
    private void showBirthdayDialog() {

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.CHINA);



        Calendar curr = Calendar.getInstance();
        curr.set(Calendar.YEAR,curr.get(Calendar.YEAR)-18);
        Date date18=curr.getTime();


        Calendar curr2 = Calendar.getInstance();
        curr2.set(Calendar.YEAR,curr2.get(Calendar.YEAR)-80);
        Date date80=curr2.getTime();


        String time18 = sdf.format(date18);
        String time80 = sdf.format(date80);
        String date = time18.split(" ")[0];


        CustomDatePicker datePicker= new CustomDatePicker(this,new CustomDatePicker.ResultHandler() {
            @Override
            public void handle(String time) {
                LogUtils.i(TAG,time);
                birthday = time.substring(0,10);

            }
        }, time80, time18);
        // datePicker.setSelectedCalender("1991-06-13");
        datePicker.showSpecificTime(false); //显示时和分
        datePicker.setIsLoop(false);
        datePicker.setDayIsLoop(true);
        datePicker.setMonIsLoop(true);
        datePicker.show(date);
        datePicker.setSelectedTime(birthday);
        datePicker.setBackgroundColor(getResources().getColor(R.color.bluetheme));
        datePicker.setListener(new TextTipDialog.ICancelOkBtListener() {
            @Override
            public void cancel(Dialog dialogView) {}//内部已经处理了
            @Override
            public void ok(Dialog dialogView) {
                ViewUtils.setTextViewStr(pd_birthday_tv,birthday);
            }
        });
    }

    private int height;
    //展示身高对话框
    private void showHeightDialog() {

        WheelViewDialog wheelViewDialog = new WheelViewDialog(this);
        wheelViewDialog.setGravity(Gravity_BUTTOM);
        List<String> list=new ArrayList<>();
        for (int i=100;i<=220;i++){
            list.add(i+" cm");
        }
        wheelViewDialog.setOffeset(1);
        wheelViewDialog.setItems(list);
        wheelViewDialog.setOnWheelViewListener(new WheelView.OnWheelViewListener() {
            @Override
            public void onSelected(int selectedIndex, String item) {
                Log.i(TAG, "selectedIndex: " + selectedIndex + ", item: " + item);
                height = NumUtils.string2Int(item.replace(" cm",""));
            }
        });


        wheelViewDialog.setListener(new TextTipDialog.ICancelOkBtListener() {
            @Override
            public void cancel(Dialog dialogView) {
                dialogView.cancel();
            }

            @Override
            public void ok(Dialog dialogView) {
                dialogView.cancel();
                ViewUtils.setTextViewStr(pd_stature_tv,height+" cm");
            }
        });
        wheelViewDialog.setSelectPosition(height-100);
        wheelViewDialog.show();
        wheelViewDialog.setBackgroundColor(getBaseContext().getResources().getColor(R.color.bluetheme));
    }

    //展示昵称框
    private void showNameDialog() {
        AddNameDialog addNameDialog=new AddNameDialog(this);
        addNameDialog.show();
        addNameDialog.setContent(userinfos.nickName);
        addNameDialog.setListener(new AddNameDialog.ICancelOkBtListener() {
            @Override
            public void cancel(Dialog dialogView) {
                LogUtils.i(TAG2,"----关闭");
                dialogView.cancel();
            }

            @Override
            public void ok(Dialog dialogView, String str) {
                LogUtils.i(TAG2,"----确定 str = " + str);

                if (TextUtils.isEmpty(str)){
                    ToastUtil.show(R.string.Nikename_cannot_be_empty);
                    return;
                }
                if (str.length()>20){
                    ToastUtil.show(R.string.nikename_over_tip);
                    return;
                }

                boolean isC = icContainName(userinfos.nickName,str);
                if (isC){
                    ToastUtil.show("Nickname already exists.");
                }else {//昵称符合要求
                    pd_name_tv.setText(str);
                    dialogView.cancel();
                }


            }
        });
    }

    private void back() {
        finish();
    }


    public boolean icContainName(String srcName,String newName){
        if (TextUtils.equals(srcName,newName)){
            return false;
        }
        List<SeneoUserinfos> users = SeneoDbUtils.getAllUserinfos();
        for(int i=0;i<users.size();i++){
            SeneoUserinfos item=users.get(i);
            String itemName=item.nickName;
            if (!TextUtils.equals(itemName,srcName)){
                if (TextUtils.equals(itemName,newName)){
                    return true;
                }
            }
        }
        return false;
    }


    //更新用户信息
    private void updateUserInfo() {

        final long userId = userinfos.user_id;
        final String nickname=pd_name_tv.getText().toString();
        final int height = Integer.parseInt(pd_stature_tv.getText().toString().replace(" cm","").trim());
        final String birthday=pd_birthday_tv.getText().toString();
        final int role = roleSelectedIndex;////0普通人 ==1运动员

        final Map<String,Serializable> paramMap=new HashMap<>();
        paramMap.put("userId", userId);
        paramMap.put("nickname", nickname);
        paramMap.put("height", height);
        paramMap.put("birthday", birthday);
        paramMap.put("profession", role);

        long mainId=userinfos.host_id;
        if (userinfos.isHost){
            mainId=0;
        }
        paramMap.put("mainId", mainId);


        //{"resultCode":112,"resultMessage":"昵称已经存在"}  Tyu
        SeneoNet.getIntance().updateInfo(this, paramMap, new HttpResponse<BaseResponse>() {
            @Override
            public void result(boolean isRequestSuccess, String requestDes, BaseResponse baseResponse, String s) {
                LogUtils.i2(TAG,"更新用户信息 s="+s);

                if (isRequestSuccess&&baseResponse!=null){

                    if (baseResponse.resultCode==0){//更新成功
                        ToastUtil.show(R.string.Modify_Success);
                        saveUserInfo(nickname,height,birthday,role);

                        //告诉外界userId的信息有变动
                        CommonEventBus commonEventBus = new CommonEventBus(TAG,SeneoMainActivity.TAG, IUserContant.ICMDS.USER_INFO_CHANGE,"userId = " + userId);
                        commonEventBus.setContent(userId);
                        EventBus.getDefault().post(commonEventBus);

                        finish();
                    }else {
                        ToastUtil.show(R.string.Modify_Failed);
                    }
                }else {
                    //更新失败
                    ToastUtil.show(R.string.Modify_Failed);
                }
            }
        });

    }

    //保存用户信息
    private void saveUserInfo(String nickname, int height, String birthday, int role) {
        userinfos.nickName=nickname;
        userinfos.height=height;
        userinfos.birthday=birthday;
        userinfos.athlete=role;
        userinfos.update();
    }
}
